from typing import List

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user, get_current_active_superuser
from app.core.database import get_db
from app.crud.crud_report_classification import report_classification
from app.models.user import User
from app.schemas.base import UnifiedResponse, success_response
from app.schemas.report_classification import (
    ReportClassification,
    ReportClassificationCreate,
    ReportClassificationUpdate
)
from app.utils.exceptions import (
    UserAlreadyExistsException,
)

router = APIRouter()


@router.get("/", response_model=UnifiedResponse[List[ReportClassification]])
async def get_report_classifications(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """
    获取报告分类列表
    """
    classifications = await report_classification.get_multi(db, skip=0, limit=1000)
    return success_response(classifications)


@router.post("/", response_model=UnifiedResponse[ReportClassification])
async def create_report_classification(
    *,
    db: AsyncSession = Depends(get_db),
    classification_in: ReportClassificationCreate,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    创建报告分类 (仅超级管理员)
    """
    # 检查分类名称是否已存在
    existing_classification = await report_classification.get_by_name(
        db, name=classification_in.name
    )
    if existing_classification:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="分类名称已存在"
        )

    classification = await report_classification.create(db, obj_in=classification_in)
    return success_response(classification)


@router.put("/{classification_id}", response_model=UnifiedResponse[ReportClassification])
async def update_report_classification(
    *,
    db: AsyncSession = Depends(get_db),
    classification_id: str,
    classification_in: ReportClassificationUpdate,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    更新报告分类 (仅超级管理员)
    """
    classification = await report_classification.get(db, id=classification_id)
    if not classification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="报告分类不存在"
        )

    # 如果更新名称，检查是否已存在
    if classification_in.name and classification_in.name != classification.name:
        existing_classification = await report_classification.get_by_name(
            db, name=classification_in.name
        )
        if existing_classification:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="分类名称已存在"
            )

    classification = await report_classification.update(
        db, db_obj=classification, obj_in=classification_in
    )
    return success_response(classification)


@router.delete("/{classification_id}", response_model=UnifiedResponse[ReportClassification])
async def delete_report_classification(
    *,
    db: AsyncSession = Depends(get_db),
    classification_id: str,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    删除报告分类 (仅超级管理员)
    """
    classification = await report_classification.get(db, id=classification_id)
    if not classification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="报告分类不存在"
        )

    classification = await report_classification.remove(db, id=classification_id)
    return success_response(classification, msg="报告分类删除成功")